#include "ring_queue.hpp"
#include "Task.hpp"
#include <string>
#include <ctime>
#include <unistd.h>

std::string self_name()
{
    char buffer[256];
    snprintf(buffer, sizeof(buffer), "pthread [0x%d]", pthread_self());
    return buffer;
}

void* productor_routine(void* rq)
{
    // ring_queue<int>* rrq = static_cast<ring_queue<int>*>(rq);
    ring_queue<Task>* rrq = static_cast<ring_queue<Task>*>(rq);
    while(1)
    {
        // int data = rand() % 100;
        // rrq->push(data);
        // std::cout << self_name() << " 推送了一个数据 : " << data << std::endl;
        int x = rand() % 8;
        int y = rand() % 8;
        int oper_code = rand() % oper.size();
        char op = oper[oper_code];
        Task t(x, y, op, mymath);
        rrq->push(t);
        std::cout << self_name() << " 推送了一个任务 : " << t.toTaskString() << std::endl;
        sleep(1);
    }
    return nullptr;
}

void* consumer_routine(void* rq)
{
    // ring_queue<int>* rrq = static_cast<ring_queue<int>*>(rq);
    ring_queue<Task>* rrq = static_cast<ring_queue<Task>*>(rq);
    while(1)
    {
        // int data;
        // rrq->pop(&data);
        // std::cout << self_name() << " 接收到一个数据 : " << data << std::endl;
        Task t;
        rrq->pop(&t);
        std::string result = t();
        std::cout << self_name() << " 完成任务 : " << result << std::endl;
    }
    return nullptr;
}

int main()
{
    srand((unsigned int)time(nullptr) ^ getpid() ^ 0x88791);
    ring_queue<Task>* rq = new ring_queue<Task>();
    pthread_t p, c;
    pthread_create(&p, nullptr, productor_routine, rq);
    pthread_create(&c, nullptr, consumer_routine, rq);

    pthread_join(p, nullptr);
    pthread_join(c, nullptr);
    return 0;
}